#include "ChkButtonBar.h"
#include "CheckButton.h"
#include "Scene.h"

using namespace std;

ChkButtonBar::ChkButtonBar(boost::shared_ptr<Scene> scene, const int size)
: m_scene(scene), m_size(size), m_value(1.0f)
{
    m_bar.clear();
}

ChkButtonBar::~ChkButtonBar(void)
{
}

bool ChkButtonBar::initialize(const Dimension& dim, const Vector3& initialPos, const Vector3& offset)
{
    for (int i=0; i<m_size; i++)
    {
        m_bar.push_back(new CheckButton(m_scene));
        m_bar[i]->setDimension(dim);
        Vector3 off = offset * static_cast<float> (i);
        m_bar[i]->setPosition(initialPos + off);
        if (!m_bar[i]->initialize())
        {
            return false;
        }
    }   

    setValue(m_value);

    return true;
}

void ChkButtonBar::prepare(float dt)
{
    for (int i=0; i<m_size; i++)
    {
        m_bar[i]->prepare(dt);
    }

    // Check if any button has been clicked
    for (int i=0; i<m_size; i++)
    {
        if (m_bar[i]->isClicked())
        {
            m_bar[i]->setClicked(false);

            // Special case for last element in bar
            if ((m_bar[i]->getButtonState() == ACTIVE) && 
                 (m_size > (i+1)) && (m_bar[i+1]->getButtonState() == IDLE))
            {
                m_bar[i]->setButtonState(IDLE);
                m_value = static_cast<float> (i*1.0f / m_size);
                break;
            }

            int index = i;

            do
            {
                m_bar[index]->setButtonState(ACTIVE);
                index--;
            } while (index>=0);

            for (int j=(i+1); j<m_size; j++)
            {
                m_bar[j]->setButtonState(IDLE);
            }

            // Update value
            m_value = static_cast<float> ((i+1.0f) / m_size);

            break;
        }
    }
}

void ChkButtonBar::render(void)
{
    for (int i=0; i<m_size; i++)
    {
        m_bar[i]->render();
    }
}

void ChkButtonBar::setValue(const float val) 
{ 
    m_value = val; 
    int lastPos = static_cast<int> (ceil(m_value * m_size));
    int i = 0;

    for (i=0; i<lastPos; i++)
    {
        if (m_bar[i] != NULL)
        {
            m_bar[i]->setButtonState(ACTIVE);
        }
    }

    for (;i<m_size; i++)
    {
        if (m_bar[i] != NULL)
        {
            m_bar[i]->setButtonState(IDLE);
        }
    }
}